package com.zhou.framework.common;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * Spring容器对象
 */
@Configuration
public class SpringFactory implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext c) {
        applicationContext = c;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }
    public static void removeBean(String name){
        DefaultListableBeanFactory acf = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        acf.removeBeanDefinition(name);
    }
    public static Object registerBean(String name,Object o){
        DefaultListableBeanFactory acf = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        // 初始化Bean定义
        BeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClassName(o.getClass().getName());

        // 注册到Spring容器中，这里必须先注册到容器中，再得到Bean进行修改，否则数据源属性不能有效修改
        acf.registerBeanDefinition(name, beanDefinition);
        o = applicationContext.getBean(name);
        return o;
    }


    public static <T> T getBean(Class<T> c){
        return getApplicationContext().getBean(c);
    }
    public static <T> T getBean(String name,Class<T> c){
        return getApplicationContext().getBean(name,c);
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name){
        return (T) getApplicationContext().getBean(name);
    }
    public static <T> List<T> getBeans(Class<T> clazz) {
        List<T> list = new ArrayList<>();
        String[] names = applicationContext.getBeanNamesForType(clazz);
        for (String name : names) {
            T bean = getBean(name, clazz);
            list.add(bean);
        }
        return list;
    }

}
